package com.gqz.equip.controller;

import com.alibaba.fastjson.JSONArray;
import com.gqz.common.core.domain.R;
import com.gqz.equip.entity.TBizcEneryEquipEntity;
import com.gqz.equip.mapstruct.TBizcEneryEquipMapstruct;
import com.gqz.equip.service.IExportExcelService;
import com.gqz.equip.service.ITBizcEneryEquipService;
import com.gqz.equip.service.ITEnInterfaceCodeService;
import com.gqz.equip.utils.ExcelUtils_new;
import com.gqz.equip.vo.ExportParamVo;
import com.gqz.equip.vo.TBizcEneryEquipVo;
import com.gqz.equip.vo.TEnInterfaceCodeVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description
 **/
@Controller
@RequestMapping("/export")
@Tag(name = "通用导出")
@Slf4j
public class ExportExcelController {

    @Autowired
    private IExportExcelService exportExcelService;
    @Autowired
    private ITBizcEneryEquipService service;
    @Autowired
    private TBizcEneryEquipMapstruct mapstruct;
    @Autowired
    private ITEnInterfaceCodeService codeService;

    @PostMapping(value = "/export-page")
    @Operation(summary = "导出查询数据", description = "导出查询数据")
    public void exportPage(@RequestBody ExportParamVo vo, HttpServletResponse response) {
        try {
            exportExcelService.exportPage(vo, response);
        } catch (Exception e) {
            log.error("分页查询检测工单列表失败！", e);
        }
    }

    //处理文件上传
    @ResponseBody//返回json数据
    @RequestMapping(value = "/excelImport", method = RequestMethod.POST)
    public R<Object> uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        String endLx = file.getContentType();
        if (file.isEmpty()) {
            return R.ok("文件为空！");
        }
        try {
            JSONArray array = ExcelUtils_new.readMultipartFile(file);
            List<TBizcEneryEquipEntity> tBizcEneryEquipEntity = ExcelUtils_new.readMultipartFile(file, TBizcEneryEquipEntity.class);
            System.out.println("导入数据为:" + array);
            for (TBizcEneryEquipEntity examData : tBizcEneryEquipEntity) {
                System.out.println("---------" + examData.toString());
            }
            List<TBizcEneryEquipVo> vos = mapstruct.toVos(tBizcEneryEquipEntity);
            List<TEnInterfaceCodeVo> tEnInterfaceCodeList = codeService.queryDictBm("EN_EQUIP");
            for (int i = 0; i < vos.size(); i++) {
                //物资管理-设备码值处理
                String yxzt = vos.get(i).getYxzt();
                String sblx = vos.get(i).getSblxmc();
                String djhszt = vos.get(i).getDjhszt();
                for (int j = 0; j < tEnInterfaceCodeList.size(); j++) {
                    if (tEnInterfaceCodeList.get(j).getValue().equals(yxzt) && tEnInterfaceCodeList.get(j).getType().equals("EN_EQUIP_YXZT")) {
                        vos.get(i).setYxzt(tEnInterfaceCodeList.get(j).getCode());
                    } else if (tEnInterfaceCodeList.get(j).getValue().equals(sblx) && tEnInterfaceCodeList.get(j).getType().equals("EN_EQUIP_SBLX")) {
                        vos.get(i).setSblx(tEnInterfaceCodeList.get(j).getCode());
                    } else if (tEnInterfaceCodeList.get(j).getValue().equals(djhszt) && tEnInterfaceCodeList.get(j).getType().equals("EN_EQUIP_DJHSZT")) {
                        vos.get(i).setDjhszt(tEnInterfaceCodeList.get(j).getCode());
                    }

                }
            }
            //调用新增接口
            service.insert(vos);
            return R.ok("数据导入成功...");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败!");
        }
    }

    @GetMapping(value = "/downloadTemplate")
    public void downFrozenTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "物资设备.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("content-type:octet-stream");
        //文件在项目中的存放路径
        //String filePath = getClass().getResource("com/tellhow/om/equip/file/物资设备.xlsx").getPath();
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        } else {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // 随着“附件”文件将下载。可能会显示一个“另存为”基于浏览器的设置对话框。
        InputStream inputStream = getClass().getResourceAsStream("/物资设备.xlsx");
        int b = 0;
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            bis = new BufferedInputStream(inputStream);
            os = response.getOutputStream();
            if (inputStream != null) {
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}



